#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

边框渲染工具
用于动态生成适应终端宽度的边框
"""

import unicodedata
import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()




def safe_str(text):
    """安全字符串转换"""
    if isinstance(text, bytes):
        return text.decode('utf-8', errors='ignore')
    return str(text)

def display_width(text):
    """计算Unicode字符显示宽度，保证边框对齐"""
    width = 0
    for ch in safe_str(text):
        # 组合字符宽度为0
        if unicodedata.category(ch) == 'Mn':
            continue
        eaw = unicodedata.east_asian_width(ch)
        if eaw in ('W', 'F'):
            width += 2
        else:
            # 常见Emoji在某些终端宽度为2，粗略判断
            if ord(ch) >= 0x1F300 and ord(ch) <= 0x1FAFF:
                width += 2
            else:
                width += 1
    return width

def render_box(lines, padding=1, style='double'):
    """
    渲染动态边框
    
    Args:
        lines: 文本行列表
        padding: 内边距
        style: 边框样式 ('single', 'double', 'rounded')
    
    Returns:
        渲染后的边框字符串
    """
    # 边框字符定义
    styles = {
        'single': {
            'top_left': '┌', 'top_right': '┐', 'bottom_left': '└', 'bottom_right': '┘',
            'horizontal': '─', 'vertical': '│', 'cross': '┼',
            'top_cross': '┬', 'bottom_cross': '┴', 'left_cross': '├', 'right_cross': '┤'
        },
        'double': {
            'top_left': '╔', 'top_right': '╗', 'bottom_left': '╚', 'bottom_right': '╝',
            'horizontal': '═', 'vertical': '║', 'cross': '╬',
            'top_cross': '╦', 'bottom_cross': '╩', 'left_cross': '╠', 'right_cross': '╣'
        },
        'rounded': {
            'top_left': '╭', 'top_right': '╮', 'bottom_left': '╰', 'bottom_right': '╯',
            'horizontal': '─', 'vertical': '│', 'cross': '┼',
            'top_cross': '┬', 'bottom_cross': '┴', 'left_cross': '├', 'right_cross': '┤'
        }
    }
    
    chars = styles.get(style, styles['single'])
    
    # 计算最大宽度
    inner_width = 0
    for line in lines:
        inner_width = max(inner_width, display_width(line))
    inner_width += padding * 2

    # 构造边框
    top = chars['top_left'] + chars['horizontal'] * inner_width + chars['top_right']
    bottom = chars['bottom_left'] + chars['horizontal'] * inner_width + chars['bottom_right']
    
    out_lines = [top]
    for line in lines:
        # 左右填充
        left_pad = ' ' * padding
        line_text = safe_str(line)
        fill = inner_width - display_width(line_text) - padding
        right_pad = ' ' * max(fill, 1)
        out_lines.append(chars['vertical'] + left_pad + line_text + right_pad + chars['vertical'])
    out_lines.append(bottom)
    
    return '\n'.join(out_lines)

def render_separator_box(lines, padding=1, style='double'):
    """
    渲染带分隔线的边框
    
    Args:
        lines: 文本行列表，第一行作为标题
        padding: 内边距
        style: 边框样式
    
    Returns:
        渲染后的边框字符串
    """
    if not lines:
        return ""
    
    styles = {
        'single': {
            'top_left': '┌', 'top_right': '┐', 'bottom_left': '└', 'bottom_right': '┘',
            'horizontal': '─', 'vertical': '│', 'cross': '┼',
            'top_cross': '┬', 'bottom_cross': '┴', 'left_cross': '├', 'right_cross': '┤'
        },
        'double': {
            'top_left': '╔', 'top_right': '╗', 'bottom_left': '╚', 'bottom_right': '╝',
            'horizontal': '═', 'vertical': '║', 'cross': '╬',
            'top_cross': '╦', 'bottom_cross': '╩', 'left_cross': '╠', 'right_cross': '╣'
        }
    }
    
    chars = styles.get(style, styles['single'])
    
    # 计算最大宽度
    inner_width = 0
    for line in lines:
        inner_width = max(inner_width, display_width(line))
    inner_width += padding * 2

    # 构造边框
    top = chars['top_left'] + chars['horizontal'] * inner_width + chars['top_right']
    separator = chars['left_cross'] + chars['horizontal'] * inner_width + chars['right_cross']
    bottom = chars['bottom_left'] + chars['horizontal'] * inner_width + chars['bottom_right']
    
    out_lines = [top]
    
    # 添加第一行（标题）
    if lines:
        line_text = safe_str(lines[0])
        left_pad = ' ' * padding
        fill = inner_width - display_width(line_text) - padding
        right_pad = ' ' * max(fill, 1)
        out_lines.append(chars['vertical'] + left_pad + line_text + right_pad + chars['vertical'])
        
        # 如果有更多行，添加分隔线
        if len(lines) > 1:
            out_lines.append(separator)
            
            # 添加其余行
            for line in lines[1:]:
                line_text = safe_str(line)
                left_pad = ' ' * padding
                fill = inner_width - display_width(line_text) - padding
                right_pad = ' ' * max(fill, 1)
                out_lines.append(chars['vertical'] + left_pad + line_text + right_pad + chars['vertical'])
    
    out_lines.append(bottom)
    return '\n'.join(out_lines)

def get_terminal_width():
    """获取终端宽度"""
    try:
        return os.get_terminal_size().columns
    except:
        return 80  # 默认宽度

def generate_logo_with_dynamic_borders():
    """生成带动态边框的logo"""
    ascii_art = [
        "██████╗ ██████╗ ██╗██╗   ██╗██╗██╗     ███████╗ ██████╗ ███████╗",
        "██╔══██╗██╔══██╗██║██║   ██║██║██║     ██╔════╝██╔════╝ ██╔════╝",
        "██████╔╝██████╔╝██║██║   ██║██║██║     █████╗  ██║  ███╗█████╗  ",
        "██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██║██║     ██╔══╝  ██║   ██║██╔══╝  ",
        "██║     ██║  ██║██║ ╚████╔╝ ██║███████╗███████╗╚██████╔╝███████╗",
        "╚═╝     ╚═╝  ╚═╝╚═╝  ╚═══╝  ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚══════╝",
        "",
        "███╗   ███╗ █████╗ ██╗███╗   ██╗████████╗███████╗███╗   ██╗ █████╗ ███╗   ██╗ ██████╗███████╗",
        "████╗ ████║██╔══██╗██║████╗  ██║╚══██╔══╝██╔════╝████╗  ██║██╔══██╗████╗  ██║██╔════╝██╔════╝",
        "██╔████╔██║███████║██║██╔██╗ ██║   ██║   █████╗  ██╔██╗ ██║███████║██╔██╗ ██║██║     █████╗  ",
        "██║╚██╔╝██║██╔══██║██║██║╚██╗██║   ██║   ██╔══╝  ██║╚██╗██║██╔══██║██║╚██╗██║██║     ██╔══╝  ",
        "██║ ╚═╝ ██║██║  ██║██║██║ ╚████║   ██║   ███████╗██║ ╚████║██║  ██║██║ ╚████║╚██████╗███████╗",
        "╚═╝     ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝   ╚═╝   ╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝╚══════╝"
    ]
    
    # 主标题框
    title_lines = [
        "",
        "🔐 Linux Privilege Maintenance Tool v1.0 🔐",
        "",
        "⚡ Advanced Persistence Framework  |  🛡️ Security Research Tool  |  🔧 Modular Design",
        "",
        "🎯 Target: Linux Systems          |  📊 Detection & Deployment   |  ⚠️  Authorized Use"
    ]
    
    # 功能特性框
    feature_lines = [
        "🚀 FEATURES 🚀",
        "🔍 System Detection    │  🔑 SSH Backdoors      │  📁 File Persistence",
        "🌐 Web Shells         │  ⏰ Cron Jobs          │  🔧 Service Backdoors",
        "👤 User Accounts      │  🔐 PAM Modules        │  📋 Comprehensive Reports"
    ]
    
    # 免责声明框
    disclaimer_lines = [
        "⚠️  DISCLAIMER ⚠️",
        "This tool is designed for authorized security testing and educational purposes only.",
        "Users are responsible for ensuring compliance with applicable laws and regulations.",
        "Unauthorized use is strictly prohibited and may result in legal consequences."
    ]
    
    # 组合输出
    result = []
    
    # ASCII艺术字
    for line in ascii_art:
        result.append(line)
    result.append("")
    
    # 主标题框
    result.append(render_box(title_lines, padding=1, style='double'))
    result.append("")
    
    # 功能特性框
    result.append(render_separator_box(feature_lines, padding=1, style='single'))
    result.append("")
    
    # 免责声明框
    result.append(render_separator_box(disclaimer_lines, padding=1, style='single'))
    
    return '\n'.join(result)

if __name__ == '__main__':
    # 测试函数
    print(generate_logo_with_dynamic_borders())